using SqlSugar;
using System.Data;
using DbType = SqlSugar.DbType;

namespace ChatBackend.Infrastructure
{
    public static class SqlSugarExtensions
    {
        public static void ConfigureSqliteForDateTime(this ISqlSugarClient db)
        {
            // 配置日志记录，暂时移除DateTime转换逻辑
            // 因为SqlSugar 5.1.4.196版本的AOP API有变化
            // DateTime字段将通过EntityService在ConfigureExternalServices中处理
        }

        public static ISqlSugarClient CreateSafeSqliteClient(string connectionString)
        {
            var config = new ConnectionConfig()
            {
                ConnectionString = connectionString,
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                MoreSettings = new ConnMoreSettings()
                {
                    IsAutoRemoveDataCache = true,
                    IsWithNoLockQuery = true,
                    DisableNvarchar = true,
                    SqliteCodeFirstEnableDefaultValue = true
                },
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    EntityService = (c, p) =>
                    {
                        // 统一处理DateTime字段
                        if (p.PropertyInfo.PropertyType == typeof(DateTime) ||
                            p.PropertyInfo.PropertyType == typeof(DateTime?))
                        {
                            p.DataType = "TEXT";
                        }
                    },
                    // 自定义类型映射
                    EntityNameService = (type, entity) =>
                    {
                        // 可以在这里自定义表名
                    }
                }
            };

            var db = new SqlSugarClient(config);
            
            // 应用DateTime配置
            db.ConfigureSqliteForDateTime();
            
            // 配置日志
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine($"[SQL] {sql}");
                if (pars != null && pars.Any())
                {
                    Console.WriteLine($"[Parameters] {string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"))}");
                }
            };

            // 配置错误处理
            db.Aop.OnError = (exp) =>
            {
                Console.WriteLine($"[SQL Error] {exp.Message}");
                Console.WriteLine($"[SQL] {exp.Sql}");
            };

            return db;
        }
    }
}
